<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="配置名称" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="配置方式" prop="type">
      <el-select v-model="ruleForm.type" @change="handleTypeChange">
        <el-option label="输入" :value="1" />
        <el-option label="上传" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="值" prop="property">
      <el-input v-model="ruleForm.property" v-if="ruleForm.type === 1" />
      <UploadImg v-model="ruleForm.property" @on-success="handleSuccess(ruleFormRef)" v-else />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue'
import { UploadImg } from '@/components/UploadFile'
import type { FormInstance, FormRules } from 'element-plus'

interface RuleForm {
  name: string
  id: number
  property: string
  type: number
}

const emit = defineEmits(['success'])
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})

watch(
  () => props.data,
  (newVal) => {
    console.log('newVal', newVal)
    nextTick(() => {
      ruleForm.name = newVal.name || ''
      ruleForm.id = newVal.id || 0
      ruleForm.property = newVal.property || ''
      ruleForm.type = parseInt(newVal.type) || 1
    })
  }
)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: props.data.name || '',
  id: props.data.id || 0,
  property: props.data.property || '',
  type: parseInt(props.data.type) || 1
})

const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
  property: [{ required: true, message: '请输入或上传配置的内容', trigger: 'change' }]
})

const submitForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      emit('success', ruleForm)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleSuccess = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  console.log('ruleForm.property', ruleForm.property)
  if (ruleForm.property) {
    formEl.clearValidate('property')
  } else {
    formEl.validateField('property')
  }
}

const handleTypeChange = () => {
  ruleForm.property = ''
}

defineExpose({
  submitForm
})
</script>
